import React, { useState, useEffect, useRef } from 'react'

const VolunteerDashboard = ({ currentUser, onLogout }) => {
  const [showServiceRecords, setShowServiceRecords] = useState(false)
  const [videoCallActive, setVideoCallActive] = useState(false)
  const localVideoRef = useRef(null)
  const [localStreamRef, setLocalStreamRef] = useState(null)
  const [appointments, setAppointments] = useState([
    {
      id: 1,
      time: '2024-01-20 14:00',
      place: '北京市朝阳区',
      event: '帮助识别药品说明书',
      serviceMethod: '视频通话',
      status: '待接受'
    },
    {
      id: 2,
      time: '2024-01-21 09:30',
      place: '北京市海淀区',
      event: '帮助购物时识别商品标签',
      serviceMethod: '语音通话',
      status: '待接受'
    }
  ])

  const [serviceRecords, setServiceRecords] = useState([
    {
      id: 1,
      time: '2024-01-16 14:30',
      method: '视频通话',
      duration: '12分钟',
      event: '帮助识别药品说明书',
      rating: 5,
      helper: '王女士',
      status: '已完成'
    },
    {
      id: 2,
      time: '2024-01-16 10:15',
      method: '语音通话',
      duration: '8分钟',
      event: '帮助识别公交站牌',
      rating: 5,
      helper: '李先生',
      status: '已完成'
    }
  ])

  const startVideoCall = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
      setLocalStreamRef(stream)
      setVideoCallActive(true)
    } catch (e) {
      alert('无法打开摄像头/麦克风：' + (e.message || '请检查权限'))
    }
  }

  const stopVideoCall = () => {
    setVideoCallActive(false)
    if (localStreamRef) {
      localStreamRef.getTracks().forEach(t => t.stop())
      setLocalStreamRef(null)
    }
  }

  const acceptAppointment = (id) => {
    setAppointments(prev => prev.map(a => a.id === id ? { ...a, status: '已接受' } : a))
  }

  const getVolunteerLevel = (score) => {
    if (score >= 1000) return { level: '钻石', title: '无私奉献者', rank: '1-10' }
    if (score >= 500) return { level: '黄金', title: '热心助人者', rank: '11-50' }
    if (score >= 200) return { level: '白银', title: '乐于助人者', rank: '51-200' }
    if (score >= 100) return { level: '青铜', title: '新手志愿者', rank: '201-500' }
    return { level: '新手', title: '初来乍到', rank: '500+' }
  }

  const volunteerInfo = getVolunteerLevel(currentUser.rating || 0)
  const totalHours = Math.floor((currentUser.serviceCount || 0) * 0.2) // 估算每次服务12分钟

  if (showServiceRecords) {
    return (
      <div className="dashboard">
        <div className="user-header">
          <div className="user-avatar">{currentUser.avatar}</div>
          <div className="user-info">
            <h2>{currentUser.name}</h2>
            <p>志愿者 · 服务等级: {currentUser.rating}⭐</p>
            <p>已服务: {currentUser.serviceCount} 次</p>
          </div>
          <button className="btn btn-logout" onClick={onLogout}>
            退出登录
          </button>
        </div>

        <div className="dashboard-content">
          <div className="help-section">
            <h3>📋 详细志愿记录</h3>
            <button className="btn btn-secondary" onClick={() => setShowServiceRecords(false)} style={{ marginBottom: 16 }}>
              ← 返回主页面
            </button>
            {serviceRecords.map(record => (
              <div key={record.id} className="help-record" style={{ marginBottom: 16 }}>
                <div className="record-header">
                  <span className={`record-status ${record.status === '已完成' ? 'completed' : 'pending'}`}>
                    {record.status}
                  </span>
                  <span className="record-time">{record.time}</span>
                </div>
                <p className="record-description">{record.event}</p>
                <div className="record-details">
                  <span>👤 求助者: {record.helper}</span>
                  <span>📞 方式: {record.method}</span>
                  <span>⏱️ 时长: {record.duration}</span>
                  <span>⭐ 评分: {record.rating}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="dashboard">
      <div className="user-header">
        <div className="user-avatar">{currentUser.avatar}</div>
        <div className="user-info">
          <h2>{currentUser.name}</h2>
          <p>志愿者 · 服务等级: {currentUser.rating}⭐</p>
          <p>已服务: {currentUser.serviceCount} 次</p>
        </div>
        <button className="btn btn-logout" onClick={onLogout}>
          退出登录
        </button>
      </div>

      <div className="dashboard-content">
        {/* 个人中心 */}
        <div className="help-section">
          <h3>👤 个人中心</h3>
          <div className="service-stats">
            <div className="stat-card">
              <div className="stat-number">{currentUser.serviceCount || 0}</div>
              <div className="stat-label">总志愿次数</div>
            </div>
            <div className="stat-card">
              <div className="stat-number">{totalHours}</div>
              <div className="stat-label">总志愿时长(小时)</div>
            </div>
            <div className="stat-card">
              <div className="stat-number">{currentUser.rating || 0}</div>
              <div className="stat-label">积分</div>
            </div>
            <div className="stat-card">
              <div className="stat-number">{volunteerInfo.level}</div>
              <div className="stat-label">志愿者等级</div>
            </div>
          </div>
          <div className="accessibility-info" style={{ marginTop: 16 }}>
            <h3>个人荣誉</h3>
            <ul>
              <li>🏆 称号: {volunteerInfo.title}</li>
              <li>📊 排名: {volunteerInfo.rank}</li>
              <li>💎 积分: {currentUser.rating || 0}</li>
            </ul>
          </div>
          <button 
            className="btn btn-primary" 
            onClick={() => setShowServiceRecords(true)}
            style={{ marginTop: 16 }}
          >
            📋 查看详细志愿记录
          </button>
        </div>

        {/* 视频通话 */}
        <div className="help-section">
          <h3>📞 与视障人士视频通话</h3>
          {!videoCallActive ? (
            <div className="accessibility-info">
              <h3>电话提醒</h3>
              <ul>
                <li>🔔 当有视障人士发起视频通话时，系统会通过电话提醒您</li>
                <li>📱 您也可以主动发起视频通话测试</li>
                <li>💡 建议保持手机畅通，及时响应求助</li>
              </ul>
              <button className="btn btn-primary" onClick={startVideoCall} style={{ marginTop: 12 }}>
                开始视频通话测试
              </button>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <video ref={localVideoRef} autoPlay playsInline muted style={{ width: '100%', borderRadius: 12, background: '#000' }} />
              <button className="btn btn-secondary" onClick={stopVideoCall}>
                结束通话
              </button>
              <div className="empty-state" style={{ marginTop: 8 }}>
                <div className="empty-icon">📡</div>
                <h4>演示模式</h4>
                <p>已打开本地摄像头。对接真实通话需后台信令与视障人士端。</p>
              </div>
            </div>
          )}
        </div>

        {/* 预约中心 */}
        <div className="help-section">
          <h3>📅 预约中心</h3>
          {appointments.length === 0 ? (
            <div className="empty-state">
              <div className="empty-icon">📅</div>
              <h4>暂无预约</h4>
              <p>目前没有视障人士的预约请求</p>
            </div>
          ) : (
            <div className="service-history">
              {appointments.map(appointment => (
                <div key={appointment.id} className="history-item">
                  <div className="history-header">
                    <strong>{appointment.event}</strong>
                    <span className="history-time">{appointment.time}</span>
                  </div>
                  <div className="history-details">
                    <span>📍 地点: {appointment.place}</span>
                    <span>📞 服务方式: {appointment.serviceMethod}</span>
                    <span>⏰ 时间: {appointment.time}</span>
                  </div>
                  <div className="button-group" style={{ marginTop: 12 }}>
                    <button 
                      className="btn btn-primary" 
                      onClick={() => acceptAppointment(appointment.id)}
                      disabled={appointment.status === '已接受'}
                    >
                      {appointment.status === '已接受' ? '已接受' : '接受预约'}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 设置 */}
        <div className="help-section">
          <h3>⚙️ 设置</h3>
          <div className="settings-grid">
            <div className="setting-card">
              <h4>服务偏好</h4>
              <div className="setting-options">
                <label>
                  <input type="checkbox" defaultChecked /> 文字识别
                </label>
                <label>
                  <input type="checkbox" defaultChecked /> 环境描述
                </label>
                <label>
                  <input type="checkbox" /> 购物协助
                </label>
                <label>
                  <input type="checkbox" /> 紧急求助
                </label>
              </div>
            </div>
            <div className="setting-card">
              <h4>通知设置</h4>
              <div className="setting-options">
                <label>
                  <input type="checkbox" defaultChecked /> 新求助通知
                </label>
                <label>
                  <input type="checkbox" defaultChecked /> 服务完成通知
                </label>
                <label>
                  <input type="checkbox" /> 系统消息
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default VolunteerDashboard
